from flask import Blueprint, jsonify, request
from flaskapp.services.task import task_delete, task_get, task_insert, task_edit, task_getPIDByID, task_getStartInfo, task_update_pid, task_getTaskServerByID
from flask_jwt_extended import get_jwt_identity, jwt_required
import requests

from flaskapp.plugins.SetupLogging import setup_logging

logger = setup_logging(__file__)




task_bp = Blueprint('task', __name__)

@task_bp.route('/api/task', methods=['GET'])
@jwt_required()
def get_data():
    try:
        if request.is_json:
            json_data = request.get_json()
            pageIndex = json_data.get('pageIndex', 1)
            pageSize = json_data.get('pageSize', 10)
            targetType = json_data.get('targetType', None)
        else:
            pageIndex = request.args.get('pageIndex', default=1, type=int)
            pageSize = request.args.get('pageSize', default=10, type=int)
            targetType = request.args.get('targetType', default=None, type=str)
        
        logger.info(f"Request received for pageIndex: {pageIndex}, pageSize: {pageSize}, targetType: {targetType}")
        data = task_get(pageIndex=pageIndex, pageSize=pageSize, targetType=targetType)
        return jsonify({"code": 0, "data": data})
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"error": "Failed to get data"})


@task_bp.route('/api/task', methods=['POST'])
@jwt_required()
def post_data():
    try:
        if request.is_json:
            data = request.get_json()
        else:
            data = {
                "taskServer": request.args.get('taskServer'),
                "targetType": request.args.get('targetType'),
                "modelFrame": request.args.get('modelFrame'),
                "media": request.args.get('media'),
                "mediaID": request.args.get('mediaID'),
                "confidence": request.args.get('confidence', type=float),
                "pid": request.args.get('pid'),
                "fps": request.args.get('fps'),
            }
        
        if None in (data.get('taskServer'), data.get('targetType'), data.get('modelFrame'), data.get('media'), data['confidence']):
            raise ValueError("Missing data in request")

        result = task_insert(data['taskServer'], data['targetType'], data['modelFrame'], data['media'], data['mediaID'], data['confidence'], data.get('pid'), data['fps'])
        if result:
            return jsonify({"code": 0, "success": True})
        else:
            return jsonify({"error": "Failed to insert data"})
    except ValueError as ve:
        logger.error(f"Validation error: {ve}")
        return jsonify({"error": str(ve)})
    except Exception as e:
        logger.error(f"Error inserting data: {e}")
        return jsonify({"error": "Failed to insert data"})



@task_bp.route('/api/task/<string:task_id>', methods=['DELETE'])
@jwt_required()
def delete_data(task_id):
    try:
        result = task_delete(task_id)
        if result:
            return jsonify({"code": 0, "success": True})
        else:
            return jsonify({"error": "Task not found"})
    except Exception as e:
        logger.error(f"Error deleting data: {e}")
        return jsonify({"error": "Failed to delete data"})

# 编辑任务接口
@task_bp.route('/api/task/<string:task_id>', methods=['PUT'])
@jwt_required()
def edit_data(task_id):
    try:
        if request.is_json:
            data = request.get_json()
        else:
            data = {
                "taskServer": request.args.get('taskServer'),
                "targetType": request.args.get('targetType'),
                "modelFrame": request.args.get('modelFrame'),
                "media": request.args.get('media'),
                "confidence": request.args.get('confidence', type=float),
                "fps": request.args.get('fps'),
            }

        if None in (data.get('taskServer'), data.get('targetType'), data.get('modelFrame'), data.get('media'), data['confidence']):
            raise ValueError("Missing data in request")

        result = task_edit(task_id, data['taskServer'], data['targetType'], data['modelFrame'], data['media'], data['confidence'], data['fps'])
        if result:
            return jsonify({"code": 0, "success": True})
        else:
            return jsonify({"error": "Task not found or failed to update"})
    except ValueError as ve:
        logger.error(f"Validation error: {ve}")
        return jsonify({"error": str(ve)})
    except Exception as e:
        logger.error(f"Error editing data: {e}")
        return jsonify({"error": "Failed to edit data"})

# 启动任务接口
@task_bp.route('/api/task/<string:task_id>/start', methods=['POST'])
@jwt_required()
def start_task(task_id):
    try:
        taskServer = task_getTaskServerByID(task_id)
        startInfo = task_getStartInfo(task_id)
        response = requests.post(url=taskServer+"/api/detect/start", json=startInfo)
        response.raise_for_status()  # 检查请求是否成功
        updatePIDFlag = task_update_pid(task_id, response.json().get('pid'))

        if response and updatePIDFlag:
            return response.json()
    except Exception as e:
        logger.error(f"Error starting task: {e}")
        return jsonify({"error": "Failed to start task"})


# 停止任务接口
@task_bp.route('/api/task/<string:task_id>/stop', methods=['POST'])
@jwt_required()
def stop_task(task_id):
    try:
        taskServer = task_getTaskServerByID(task_id)
        pid = task_getPIDByID(task_id)
        response = requests.post(url=taskServer+"/api/detect/stop", json={'pid': f'{pid}'})
        response.raise_for_status()  # 检查请求是否成功
        updatePIDFlag = task_update_pid(task_id, response.json().get('pid'))

        if response and updatePIDFlag:
            return response.json()
    except Exception as e:
        logger.error(f"Error stopping task: {e}")
        return jsonify({"error": "Failed to stop task"})



# 新增检查进程状态的接口
@task_bp.route('/api/task/status/<string:task_id>', methods=['POST'])
@jwt_required()
def check_task_status(task_id):
    try:
        taskServer = task_getTaskServerByID(task_id)
        pid = task_getPIDByID(task_id)
        response = requests.post(url=taskServer+"/api/detect/status", json={'pid': f'{pid}'})
        response.raise_for_status()  # 检查请求是否成功
        return response.json()  # 返回 JSON 响应数据
    except requests.RequestException as e:
        logger.error(f"Error checking task status: {e}")
        return jsonify({"error": "Failed to check status"})
    
